package data

import (
	"review-service/internal/conf"
	"review-service/internal/data/mysqlquery"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/wire"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewGreeterRepo, NewReviewRepo, NewImageRepo, NewDb, NewMino)

// Data .“
type ReviewRepo struct {
	log   *log.Helper
	db    *mysqlquery.Query
	minio *minio.Client
}


func NewDb(c *conf.Data, logger log.Logger) (*mysqlquery.Query, func(), error) {
	db, err := gorm.Open(mysql.Open(c.Database.Source), &gorm.Config{})
	if err != nil {
		log.NewHelper(logger).Error("failed to get db", err.Error())
		return nil, nil, err
	}
	cleanup := func() {
		sqlDB, err := db.DB()
		if err != nil {
			log.NewHelper(logger).Fatal("failed to get sql db", err.Error())
			return
		}
		// 在程序退出或不再需要连接时关闭
		defer sqlDB.Close()
		log.NewHelper(logger).Info("closing the data resources")
	}
	mysqlquery.SetDefault(db)
	log.NewHelper(logger).Info("db connected successfully")
	return mysqlquery.Q, cleanup, nil
}

func NewMino(c *conf.Data, logger log.Logger) (*minio.Client, error) {
	minioClient, err := minio.New(c.Minio.Endpoint, &minio.Options{
		Secure: false,
		Creds:  credentials.NewStaticV4(c.Minio.UserName, c.Minio.Password, ""),
	})
	if err != nil {
		log.NewHelper(logger).Error("failed to get minio client", err.Error())
		return nil, err
	}
	log.NewHelper(logger).Info("minio client connected successfully")
	return minioClient, nil

}
